<?php
// 应用公共文件
use app\common\lib\JwtUtil;
use think\Response;

/**返回json对象
 * @param $data
 * @return Response
 */
function echoJson($data): Response
{
    return Response::create($data, 'json');
}

/**成功
 * @param array $data 数据
 * @param string $message 消息
 * @param int $code 状态吗
 * @return array
 */
function successJson(array $data = [], string $message = '请求成功', int $code = 200): array
{
    return ['code' => $code, 'message' => $message, 'data' => $data];
}

/**失败
 * @param string $message
 * @param int $code
 * @param array $data
 * @return array
 */
function errorJson(string $message = '请求失败', int $code = 100, array $data = []): array
{
    return ['code' => $code, 'message' => $message, 'data' => $data];
}

function md5Password(string $password): string
{
    return md5(md5($password).'_robot');
}

function createToken(int $uid): string
{
    $aud = 'admin';
    $iss = 'robot_iss';
    $key = env('user_jwt.key')??'giweFhsi3HIFi1';
    return JwtUtil::instance()->setAud($aud)->setIss($iss)->setKey($key)->createToken($uid, 86400 * 2);
}

function deToken(string $token): object
{
    $aud = 'admin';
    $iss = 'brz-robot_iss-user';
    $key = env('user_jwt.key')??'giweFhsi3HIFi1';
    return JwtUtil::instance()->setKey($key)->setIss($iss)->setAud($aud)->verify(strval($token));

}
function sendHttp($url, $params, $method = 'get', $timeout = 3)
{
    if (null == $url) return null;

    $curl = curl_init();

    if ('get' == $method) {//以GET方式发送请求
        curl_setopt($curl, CURLOPT_URL, $url);
    } else {//以POST方式发送请求
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);//设置传送的参数
    }

    curl_setopt($curl, CURLOPT_HEADER, false);//设置header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);//设置等待时间

    $res = curl_exec($curl);//运行curl
    $err = curl_error($curl);
    if (false === $res || !empty($err)) {
        $Errno = curl_errno($curl);
        $Info = curl_getinfo($curl);
        curl_close($curl);

        //print_r($Info);

        return $err. ' result: ' . $res . 'error_msg: '.$Errno;
    }
    curl_close($curl);//关闭curl
    return $res;
}

function tp_page(int $listRows = 10, int $page = 1): array
{
    return [
        'list_rows' => (int)input('list_rows', $listRows),
        'page' => (int)input('page', $page),
    ];
}

function strReplaceMessage($str,$message,$p = ''): string
{
    return trim(str_replace($str,$p,$message));
}
